//
//  ProductEditImageCell.m
//  AFNetworking
//
//  Created by admin on 2020/4/28.
//

#import "ProductEditImageCell.h"
#import "DefualCollectionViewCell.h"
#import "EditProductDefImgCell.h"
@implementation ProductEditImageCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self configUI];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}
-(void)configUI{
 [self.contentView addSubview:self.collectionView];
    [self.contentView addSubview:self.titleLab];
    [self.contentView addSubview:self.notNullIcon];
    [self.contentView addSubview:self.rightArrow];
   
}

-(UILabel *)titleLab{
    if (!_titleLab) {
        _titleLab = [UILabel new];
        _titleLab.font = FONT_SYS14;
        _titleLab.textColor = COLOR_33;
    }
    return _titleLab;
}

-(UIImageView *)notNullIcon{
    if (!_notNullIcon) {
        _notNullIcon = [UIImageView new];
    }
    return _notNullIcon;
}
-(UIImageView *)rightArrow{
    if (!_rightArrow) {
        _rightArrow = [UIImageView new];
        [_rightArrow setImage:[UIImage imageWithIcon:@"fa-angle-right" backgroundColor:[UIColor clearColor] iconColor:COLOR_99 andSize:CGSizeMake(18, 18)]];
    }
    return _rightArrow;
}


-(void)reload:(ProductEditData*)data{
    _titleLab.text = data.title;
}

-(NSMutableArray *)datalist{
    if (!_datalist) {
        _datalist = [@[@"0000",@"10000",@"20000"] mutableCopy];
    }
    return _datalist;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[EditProductDefImgCell class] forCellWithReuseIdentifier:@"EditProductDefImgCell"];
    }
    return _collectionView;
}
-(UICollectionViewFlowLayout *)flowLayout{
    if (!_flowLayout) {
        _flowLayout = [UICollectionViewFlowLayout new];
        _flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    }
    return _flowLayout;
}

#pragma mark UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSInteger count = (self.datalist.count+1)<=5 ? (self.datalist.count+1) : 5;
    return count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
     EditProductDefImgCell * cell = (EditProductDefImgCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"EditProductDefImgCell" forIndexPath:indexPath];
    cell.backgroundColor = UIColor.ug_random;

    
    if (indexPath.row<self.datalist.count) {
        //添加长按手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(moveCollectionViewCell:)];
        [cell addGestureRecognizer:longPress];
        cell.deleteBtn.hidden = NO;
    }else{
        [cell.imageView setImage:UGIMAGE(@"icon_sctp")];
        cell.deleteBtn.hidden = YES;
    }
    UG_WEAKSELF
    __weak typeof(indexPath) weakindex = indexPath;
    [cell.deleteBtn ug_addEvents:UIControlEventTouchUpInside andBlock:^(id  _Nonnull sender) {
        [weakSelf.datalist removeObjectAtIndex:weakindex.row];
        [self.collectionView  reloadData];
     
    }];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(KAutoAcale(58), KAutoAcale(58));
    
}
-(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    return  indexPath.row < self.datalist.count;
}
-(void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    NSString *selectModel = self.datalist[sourceIndexPath.row];
    [_datalist removeObject:selectModel];
    [_datalist insertObject:selectModel atIndex:destinationIndexPath.row];
    
    //此处可以根据需要，上传给后台目前数据的顺序
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self selectImage:indexPath];
}
#pragma mark - 手势事件
-(void)moveCollectionViewCell:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            if (!self.isBeganMove) {
                self.isBeganMove = YES;
                //获取点击的cell的indexPath
                NSIndexPath *selectedIndexPath = [self.collectionView indexPathForItemAtPoint:[gesture locationInView:self.collectionView]];
                
                //开始移动对应的cell
                [self.collectionView beginInteractiveMovementForItemAtIndexPath:selectedIndexPath];
            }
            break;
        }
        case UIGestureRecognizerStateChanged: {
            //移动cell
            NSIndexPath *selectedIndexPath = [self.collectionView indexPathForItemAtPoint:[gesture locationInView:self.collectionView]];
            if (selectedIndexPath.row<_datalist.count) {
                [self.collectionView updateInteractiveMovementTargetPosition:[gesture locationInView:self.collectionView]];
            }
            
            break;
        }
        case UIGestureRecognizerStateEnded: {
            self.isBeganMove = false;
            //结束移动
            [self.collectionView endInteractiveMovement];
            break;
        }
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}



-(void)layoutSubviews{
    [super layoutSubviews];
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView).mas_offset(KPAND_DEF);
        make.top.mas_equalTo(self.contentView).mas_offset(KPAND_DEF);
    }];
    
    [_notNullIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleLab.mas_right);
        make.centerY.mas_equalTo(self.contentView);
    }];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView);
        make.right.mas_equalTo(self.contentView);
        make.top.mas_equalTo(self.titleLab.mas_bottom).mas_offset(KPAND_MIN);
        make.bottom.mas_equalTo(self.contentView).mas_offset(-KPAND_MIN);
    }];
    [_rightArrow mas_makeConstraints:^(MASConstraintMaker *make) {
         make.right.mas_equalTo(self.contentView).mas_offset(-KPAND_DEF);
//         make.width.mas_equalTo(KAutoAcale(30));
//         make.height.mas_equalTo(KAutoAcale(30));
         make.centerY.mas_equalTo(self.titleLab);
     }];
}

-(void)selectImage:(NSIndexPath*)index{
    
    TZImagePickerController *pickerController = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    pickerController.statusBarStyle = UIStatusBarStyleDefault;
    __weak typeof(self) weakSelf = self;
    __weak typeof(index) weakindex = index;
    [pickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photo, NSArray *assets, BOOL isSelectOriginalPhoto){
        [self.ug_ViewController.view ug_starloading];
        if (photo.count) {
            UIImage *image =  photo[0];
            DefualCollectionViewCell * cell =(DefualCollectionViewCell*) [weakSelf.collectionView cellForItemAtIndexPath:weakindex];
            [cell.imageView setImage:image];
            if (weakindex.row<weakSelf.datalist.count) {
                [weakSelf.datalist replaceObjectAtIndex:weakindex.row withObject:[NSString stringWithFormat:@"%zd",index.row]];
            }else{
                 [weakSelf.datalist addObject:[NSString stringWithFormat:@"%zd",index.row]];
            }
      
            [weakSelf.collectionView reloadData];
            
        }
        [self.ug_ViewController.view ug_stoploading];
    }];
    [self.ug_ViewController presentViewController:pickerController animated:YES completion:nil];
}
@end
